﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class WikiDetailPage : PhoneApplicationPage
    {
        private object data = null;
        private WikiList wikiList;
        private Wiki currentWiki;

        public WikiDetailPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            data = DataContext;
            if (data != null)
            {
                FindWikiById(data);
            }
            ManageButton();
        }

        private void FindWikiById(object data)
        {
            string url = null, json = null;

            currentWiki = (Wiki)data;
            if (currentWiki != null)
            {
                url = Config.Instance.WIKI_SERVICE_URL() + Config.FIND_ACTION_KEY;
                json = JsonConvert.SerializeObject(currentWiki);
            }

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(findWiki_UploadStringCompleted);
            client.UploadStringAsync(uri, "POST", json);
        }

        private void findWiki_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                wikiList = JsonConvert.DeserializeObject<WikiList>(e.Result);
                if (wikiList != null && wikiList.Count > 0)
                {
                    textBoxCreated.Text = Utility.nullToEmpty(wikiList[0].Created.ToString());
                    textBoxCreator.Text = Utility.nullToEmpty(wikiList[0].Creator.Username);
                    textBoxJudul.Text = Utility.nullToEmpty(wikiList[0].Judul);
                    textBoxIsi.Text = Utility.nullToEmpty(wikiList[0].Isi);
                    textBoxKategori.Text = Utility.nullToEmpty(wikiList[0].Kategori.Kategori);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void editButton_Click(object sender, System.EventArgs e)
        {
            Uri targetPage = new Uri("/View/WikiFormPage.xaml", UriKind.Relative);
            NavigationService.Navigate(targetPage);
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = data;
        }

        private void removeButton_Click(object sender, System.EventArgs e)
        {
            if (MessageBox.Show("Remove this record?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                DeleteCurrentWiki();
        }

        private void DeleteCurrentWiki()
        {
            string json = null, url = null;

            currentWiki = (Wiki)data;
            url = Config.Instance.WIKI_SERVICE_URL() + Config.DELETE_ACTION_KEY;
            json = JsonConvert.SerializeObject(currentWiki);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(deleteWiki_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void deleteWiki_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void logButton_Click(object sender, EventArgs e)
        {
            Uri targetPage = new Uri("/View/WikiLogPage.xaml", UriKind.Relative);
            NavigationService.Navigate(targetPage);
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = data;
        }

        private void ManageButton()
        {
            if (SavedUser.Instance.User != null && data != null)
                ApplicationBar.IsVisible = true;
            else
                ApplicationBar.IsVisible = false;
        }

    }
}